<template>
  <div id="app">
    <topbar class="topbar"></topbar>
    <div class="content">
      <div class="main">
        <h1 class="title">注册</h1>
        <el-form
          status-icon
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item prop="name" class="name_label">
            <el-input v-model="ruleForm.name" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item  prop="pwd">
            <el-input v-model="ruleForm.pwd" placeholder="密码" show-password></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-row>
              <el-col :span="18">
                <el-input v-model="ruleForm.email" placeholder="邮箱"></el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" class="sendEmailBtn" @click="sendEmail('ruleForm')" :disabled="this.sendEmailTime == 0 ? false : true">{{ !this.sendEmailTime ? "发送" : this.sendEmailTime + "s"}}</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="ruleForm.code" placeholder="验证码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即注册</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            <router-link to="/login"><el-button type="success" class="regist">登录</el-button></router-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <footbar class="footbar"></footbar>
  </div>
</template>

<script>
import topbar from '../public/topbar.vue'
import footbar from '../public/footbar.vue'
import CrypoJS from 'crypto-js'
export default {

  data() {
    var checkUserName = (rule, value, callback) => {
      this.axios.post('http://www.liujn.top/bbs/api/user/Inquire', {
        username: this.ruleForm.name
      }).then((res) => {
        if(res.data == "-1") {
          return callback(new Error('用户名已存在'))
        } else if (res.data == "0") {
          callback()
        } else {
          this.$message.error("用户名校验未知错误")
        }
      })
    }


    return {
      sendEmailTime: 0,
      ruleForm: {
        name: "",
        pwd: "",
        email: "",
        code: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "用户名只能由中文、字母、数字、下划线组成", trigger: "blur" },
          { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" },
          { validator: checkUserName, trigger: 'blur' }
        ], 
        pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { pattern: /^\w+$/,message: "密码只能由字母、数字、下划线组成", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6-20 个字符", trigger: "blur" },
        ], 
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式错误", trigger: "blur" },
        ], 
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { len: 6, message: "验证码为 6 位", trigger: "blur" },
        ]
      }
    };
  },
  methods: {
    sendEmail(formName) {
      this.$refs[formName].validateField("name", valid1 => {
        this.$refs[formName].validateField("email", valid2 => {
          if(!valid1 && !valid2) {
            this.axios.post('http://www.liujn.top/bbs/api/user/sendemail', {
              username: this.ruleForm.name,
              mailbox: this.ruleForm.email
            }).then((res) => {
              if(res.data == "-1") {
                this.$message.error("用户名已存在")
              } else if (res.data == "false") {
                this.$message.error("邮箱格式错误")
              } else if (res.data == "failure") {
                this.$message.error("邮件发送失败")
              } else if (res.data == "success") {
                this.$message.success("发送成功")
                this.sendEmailTime = 60
                for(let i = 1; i < this.sendEmailTime + 1; i++) {
                  setTimeout(() => {
                    this.sendEmailTime--
                  }, 1000 * i)
                }
              }
              else {
                this.$message.error("邮件发送未知错误")
              }
            })
          } else {
            return false;
          }
        })
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if(valid) {
          this.axios.post('http://www.liujn.top/bbs/api/user/registered',{ 
              username: this.ruleForm.name,
              password: CrypoJS.MD5(this.ruleForm.pwd).toString(),
              mailbox: this.ruleForm.email,
              code: this.ruleForm.code
            }
          ).then((res) => {
            console.log(res.data)
            if(res.data == "-1") {
              this.$message.error("用户名已存在")
            } else if (res.data == "-4") {
              this.$message.error("验证码错误")
            } else if (res.data == "0") {
              this.$message({
                message: '注册成功',
                type: "success",
                offset: 50
              }),
              this.axios.post('http://www.liujn.top/bbs/api/user/login', { 
                username: this.ruleForm.name,
                password: CrypoJS.MD5(this.ruleForm.pwd).toString()
              }).then((res) => {
                if (res.data.SessionId) {
                  this.$cookies.set("CookieId", res.data.SessionId, 60 * 60 * 24 * 30)
                  this.$cookies.set("UserName", res.data.user.username, 60 * 60 * 24 * 30)
                  this.$cookies.set("UserAvatar", res.data.user.avatar, 60 * 60 * 24 * 30)
                  this.$router.push('/article')
                }
              })
            } else if (res.data == "-5") {
              this.$message.error("验证码已过期")
            }
            else {
              this.$message.error("注册未知错误")
            }
          })
        } else {
          return false;
        }
      })
    }, 
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  name: '',
  components: {
    topbar,
    footbar
  }
};
</script>

<style scoped>

#app {
  background-image: url("../../assets/login_bg.jpg");
  background-size: 1920px 100%;
}

.sendEmailBtn {
  width: 90%;
  margin-left: 10%;
}

.content {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.demo-ruleForm {
  margin: 20px auto;
  width: 80%;
  max-width: 400px;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", 微软雅黑, Tahoma, Arial, sans-serif;
}

.regist {
  margin-left: 12px
}
.topbar {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 1;
}

.footbar {
  width: 100%;
  position: absolute;
  bottom: 0px;
}



div /deep/.el-form-item__label{
  color: white;
}

h1 {
  align-self: center;
  color: white;
  font-weight: 400;
  margin: 0px 0px 0px 20px;
  letter-spacing: 30px;
}

</style>
